<?php 
namespace app\api\controller\v1;

use think\Db;
//登录后基类
class ThirdapiController extends UserBaseController{



	public function _initialize()
    {
    	parent::_initialize();
        //因为操作时间会很长，设置php操作超时时间600秒
        set_time_limit(600);
        date_default_timezone_set("Etc/GMT");
    }




	function list(){
		$rows = \app\common\model\ThirdapiModel::$platform;
		//查找我的平台
		$all = Db::name('third_api')->where('uid',$this->user['id'])->select()->toArray();
		foreach ($rows as $key => &$value) {
			$p = get_one_by_item($all,'platform',$value['title']);
			$value['status'] = intval($p['status']);
			$value['status_title'] = \app\common\model\ThirdapiModel::$status_titles[$value['status']];
		}
		return json(['error'=>0,'msg'=>$this->lang['SUCCESS'],'data'=>$rows]);
	}




	function  del(){
		$data= input('param.');
		if(!in_array($data['type'],array(0,1,2,3)) ){
			return json(['error'=>1,'msg'=>$this->lang['TYPE'].$this->lang['ERROR']]);
		}
		$condition['uid']  = $this->user['id'];
		$condition['platform'] = \app\common\model\ThirdapiModel::$platform[$data['type']]['title'];
		Db::name('third_api')->where($condition)->update(['status'=>0]);
		return json(['error'=>0,'msg'=>$this->lang['SUCCESS']]);
	}


	function  auth(){
		$data= input('param.');
		if(!in_array($data['type'],array(0,1,2,3)) ){
			return json(['error'=>1,'msg'=>$this->lang['TYPE'].$this->lang['ERROR']]);
		}
		if(empty($data['api_key']) || empty($data['secret_key'])){
			return json(['error'=>1,'msg'=>$this->lang['API_KEY_OR_SECRET_ERROR']]);
		}
		if(empty($data['passphrase'])){
			return json(['error'=>1,'msg'=>$this->lang['PASSPHRASE_ERROR']]);
		}
		$className = \app\common\model\ThirdapiModel::$platform[$data['type']]['class'];
		$ret = $this->validateAccount($className, $data['api_key'], $data['secret_key'], $data['passphrase']);
        if ($ret[0] != 1) {
        	return json(['error'=>1,'msg'=>'API信息校验错误:' . $ret[1] ]);
        }

		$condition['uid']  = $this->user['id'];
		$condition['platform'] = \app\common\model\ThirdapiModel::$platform[$data['type']]['title'];
		$row= Db::name('third_api')->where($condition)->find();
		if($row){
			if($row['status']!=1){
				Db::name('third_api')
				        ->where('id',$row['id'])
				        ->update([
				        	'update_time'=>time(),
				        	'api_key'=>$data['api_key'],
				        	'secret_key'=>['secret_key'],
				        	'status'=>1
				        ]);
			}
		}else{
			Db::name('third_api')
				->insert([
					'uid'=>$this->user['id'],
					'update_time'=>time(),
					'api_key'=>$data['api_key'],
					'secret_key' =>$data['secret_key'],
					'passphrase' =>$data['passphrase'],
					'create_time'=>time(),
					'status'     =>1,
					'platform'   =>\app\common\model\ThirdapiModel::$platform[$data['type']]['name']
				]);
		}
		return json(['error'=>0,'msg'=>$this->lang['SUCCESS']]);
	}





	protected function validateAccount($className, $apiKey, $secret, $password)
    {
        $vendor_name = "ccxt.ccxt";
        Vendor($vendor_name);
        $class = "\ccxt\\" . $className;
        $exchange  = new $class(array(
            'apiKey' => $apiKey,
            'secret' => $secret,
            'password' => $password,
        ));

        //$this->market
        try {
            $result = $exchange->fetch_balance();
        } catch (\Exception $e) {
            //$this->error($e->getMessage());
            return array(0, $e->getMessage());
        }
        return array(1, $result);
    }
}